package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.Clazz;
import com.itheima.entity.ClazzQueryParam;
import com.itheima.entity.PageBean;
import com.itheima.mapper.ClazzMapper;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    ClazzMapper clazzMapper;
    @Override
    public PageBean page(ClazzQueryParam param) {

        PageHelper pageHelper = new PageHelper();
        pageHelper.startPage(param.getPage(),param.getPageSize());

        List<Clazz> clazzList= clazzMapper.page(param);

        Page page =(Page) clazzList;

        PageBean pageBean = new PageBean(page.getTotal(),page.getResult());

        return pageBean;



    }

    @Override
    public List<Clazz> list() {
        List<Clazz> clazzList=clazzMapper.list();
        return clazzList;
    }

    @Override
    public void delete(Integer id) {
        clazzMapper.delete(id);
    }

    @Override
    public void insert(Clazz clazz) {// 添加数据校验，确保必填字段不为空

        
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        
        // 设置班级状态
        LocalDate now = LocalDate.now();
        if (clazz.getBeginDate() != null && clazz.getEndDate() != null) {
            if (clazz.getBeginDate().isAfter(now)) {
                clazz.setStatus("未开始");
            } else if (clazz.getEndDate().isBefore(now)) {
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("在读");
            }
        }

        clazzMapper.insert(clazz);
    }

    @Override
    public Clazz getById(Integer id) {

        Clazz clazz=clazzMapper.getById(id);
        clazz.setUpdateTime(LocalDateTime.now());
        return clazz;
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }


}